#include "basedav.h"
#include "networkdav.h"
//
/*  Save file as basedav.cpp  */
/*  incomming class name BaseDav */
//
BaseDav::BaseDav(  NetworkDav * db , QWidget * parent = 0 )
{
	dbdav = db; 
    mainparent = parent;
    BeamUpsGo = false;
    numerazione = 0;
    fnumerazione = 5000;
    
    fwriteutf8(REQUESTSTREAM,"");  /* make dir if not exist on mirror or reset file to zero  */
    qt_unlink(REQUESTSTREAM);  /* remove file */
}



void BaseDav::RemoveDirorFileDav( QString removepath )
{
    /* removepath */
         QApplication::restoreOverrideCursor();
         QApplication::restoreOverrideCursor();
    
     if (!removepath.endsWith("/")) {
        QString folderfromfile = removepath.left(removepath.lastIndexOf("/"))+"/"; 
         setter.setValue("LastDirRemote",folderfromfile);
     } else {
        setter.setValue("LastDirRemote",removepath);
     }
     
    QString remotefilefolder = QString("%1%2").arg(dbdav->DummiRoot()).arg(removepath);
            remotefilefolder = remotefilefolder.replace("//","/");
    ///////////qDebug() << "#### Processing REMOVE ITEMS!!!!!!  ->" << remotefilefolder;
     
     if (!removepath.endsWith("/")) {
         DavDelete *dirorfilerm = new DavDelete(dbdav,remotefilefolder);
         connect(dirorfilerm, SIGNAL(WarningMsg(QString)), this, SLOT(ShowMessageWarning(QString)));
         connect(dirorfilerm, SIGNAL(Confirmer()), this, SLOT(ExitNextOperation()));
         return; 
     } else {
         
           ///////Gui_Remove  *remove_recursive = Gui_Remove(dbdav,remotefilefolder);
           ExitNextOperation();
          return;
     }
     
    ExitNextOperation();
}



void BaseDav::ProcessPutList( QStringList xx , QString DirReload )
{
   qDebug() << "#### Processing ->" << DirReload;
   qDebug() << "#### ProcessPutList ->" << xx;
    
    setter.setValue("LastDirRemote",DirReload);
    
     for (int i = 0; i < xx.size(); ++i)  {
                   QFileInfo prepare(xx.at(i));
                   File_Ram  *floppy = new File_Ram(prepare,dbdav->FileResolverPut(prepare,DirReload),DirReload);
                    Onwaitfile.append(floppy);
     }
     
    
     
     if (Onwaitfile.size() > 0) {
       SendPutList(0);
       return;         
     } else {
        emit  WakeUpFromList(DirReload);  
     }
}


   




void BaseDav::SendPutList( int now  )
{
    QApplication::restoreOverrideCursor();
    int bigmap = Onwaitfile.size();
    if (bigmap < 0) {
    ExitNextOperation();
    }
    
    qDebug() << "#### Processing ->" << now << " From total " << bigmap;
    if (now >= bigmap) {    
    ExitNextOperation();
    return;
    }
    
                     for ( int x = 0; x < Onwaitfile.size(); ++x ) {
                           if (now == x) {
                                if (Onwaitfile[x]->Permission()) {
                                    QApplication::restoreOverrideCursor();
                                     DavPUT *putfile = new DavPUT(dbdav,Onwaitfile[x]->GetFile(),Onwaitfile[x]->GetRemoteFile(),Onwaitfile[x]->GetPath(),mainparent);
                                            putfile->SetPosition(x);
                                     connect(putfile, SIGNAL(WarningMsg(QString)), this, SLOT(ShowMessageWarning(QString)));
                                     connect(putfile, SIGNAL(UploadFileLoop(int)), this, SLOT(SendPutList(int)));
                                     ////////////////connect(putfile, SIGNAL(SendStatus(int,int)), this, SLOT(LoadStatus(int,int)));                       
                               return;
                                } else {
                                   SendPutList( now  + 1 );
                                    return;
                                }
                           }
                     }
                     
qDebug() << "#### Last null warning line 70 basedav ....  ->" << now << " From total " << bigmap;         
ExitNextOperation();          
}


void BaseDav::ProcessVirtualMkDirList( QStringList xx , QString DirReload )
{
    
   setter.setValue("LastDirRemote",DirReload);
   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    
    for (int i = 0; i < xx.size(); ++i)  {
              QString fromroot = CheckSlash(QString("%1/%2/")
                     .arg(dbdav->Resolvpath(DirReload))
                     .arg(FileNameFix(xx.at(i))));
                    if (!MkdirLists.contains(fromroot)) {
                       MkdirLists.append(fromroot);
                    }
     }
    
    
    if (MkdirLists.size() > 0) {
        MkdirItemat(0,""); 
        return;
    }
    
    emit  WakeUpFromList(DirReload);
    
}


/* localfolder QStringList xx  ////  QString DirReload = actual dir  */
void BaseDav::ProcessMkDirList( QStringList xx , QString DirReload )
{
   qDebug() << "#### Processing ->" << DirReload;
   qDebug() << "#### ProcessMkDirList ->" << xx;
   setter.setValue("LastDirRemote",DirReload);
   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
   MkdirLists.clear();
    //////////ShowMessageWarning( QString("Load dir %1").arg(DirReload) );
    qDebug() << "#### Processing dir start ->" << xx;
    for (int i = 0; i < xx.size(); ++i)  {
              QDir dirlocal(xx.at(i));
              QString fromroot = CheckSlash(QString("%1/%2/")
                     .arg(dbdav->Resolvpath(DirReload))
                     .arg(FileNameFix(dirlocal.dirName())));
                    if (!MkdirLists.contains(fromroot)) {
                       MkdirLists.append(fromroot);
                       MkDirRecursiveFiDi(xx.at(i),fromroot);
                    }
     }
     
    if (MkdirLists.size() > 0) {
        MkdirItemat(0,""); 
        return;
    }
    
    emit  WakeUpFromList(DirReload);
}


/* const QString d   = localdir absolute  /////  QString DirStart = remote folder /xx/xx/          */
void BaseDav::MkDirRecursiveFiDi( const QString d , QString DirStart )
{
   QDir dir(d);
   if (dir.exists())
   {
      const QFileInfoList list = dir.entryInfoList();
      QFileInfo fi;
      for (int l = 0; l < list.size(); l++)
      {
         fi = list.at(l);
          QString itemfound = fi.absoluteFilePath();
          
            if (fi.isDir() && fi.fileName() != "." && fi.fileName() != "..") {   
                      QDir dirlocal(itemfound);
                      QString dirnamenowremote = CheckSlash(QString("%1/%2/").arg(DirStart).arg(FileNameFix(dirlocal.dirName())));
                      if (!MkdirLists.contains(dirnamenowremote)) {
                          /* remote MKDIR url comand   MKCOL - Webdav .... */
                          MkdirLists.append(dirnamenowremote);
                          MkDirRecursiveFiDi(itemfound,dirnamenowremote);
                      }
                
                
            }  else if (is_file(itemfound) && itemfound.contains(dir.dirName())) {
                   QFileInfo prepare(itemfound);
                   QString parest = DirStart;
                    /* remote PUT file upload ..PUT - Webdav...  list */
                    parest.append(FileNameFix(fi.fileName()));
                    File_Ram  *floppy2 = new File_Ram(prepare,parest,DirStart);
                    Onwaitfile.append(floppy2);
            } 
        
      }
      
   }
}







void BaseDav::MkdirItemat( int now  , QString fmsg )
{
    if (fmsg.size() > 0) {
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QMessageBox::information(mainparent, tr("Message From Collection."),fmsg);
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    }
    
    int bigmap = MkdirLists.size();
    if (bigmap < 0) {
    ExitNextOperation();
    return;
    }
    qDebug() << "#### Processing dir itemmmm ->" << now << " From total " << bigmap;
    if (now >= bigmap) { 
      MkdirLists.clear();        
                 if (Onwaitfile.size() > 0) {
                     SendPutList(0);
                  return;
                 }
    ExitNextOperation();  
    return;
    }
    
    
    
    
     for (int i = 0; i < MkdirLists.size(); ++i)  {
                      if (now == i) {
                      DavMKCOL *mkdircoll = new DavMKCOL(dbdav,MkdirLists.at(i));
                          mkdircoll->SetPosition(i);
                        connect(mkdircoll, SIGNAL(WarningMsg(QString)), this, SLOT(ShowMessageWarning(QString)));
                        connect(mkdircoll, SIGNAL(RemoteMkDir(int,QString)), this, SLOT(MkdirItemat(int,QString)));
                         return;
                      }
     }
                     
        
ExitNextOperation();          
}












void BaseDav::Load_Connector()
{
/* to nothing */
/*connect(buttonx, SIGNAL(clicked()), this , SLOT(Make()));*/
}

/* ################################ DIR INFO FROM PATHS (DAVM2_) #########################################*/
/*
#define DAVM1_ "OPTIONS"
#define DAVM2_ "PROPFIND"
#define DAVM3_ "PROPPATCH"
#define DAVM4_ "PUT"
#define DAVM5_ "DELETE"
#define DAVM6_ "MKCOL"
*/
/* ################################ DIR INFO FROM PATHS (DAVM2_) #########################################*/

void BaseDav::OpenDir( QString dir , bool newfile = false )
{
   
    if (newfile) {
      BeamUpsGo = true; 
    } else {
      BeamUpsGo = false;   
    }
    
    if (dir == "") {
      dir =  QString(setter.value("LastDirRemote").toString());
    }
    
    QString realpathdiplay = dbdav->ResolvDisplayPath(dir);
    QString realpathnetwww = dbdav->Resolvpath(dir);
    qDebug() << "#### realpathnetwww ->" << realpathnetwww;
     qDebug() << "#### realpathdiplay ->" << realpathdiplay;
    qDebug() << "#### dir ->" << dir;
    qDebug() << "#### net read  ";
    DavPROPFIND *xmlinfofile = new DavPROPFIND(dbdav,dir); 
    connect(xmlinfofile, SIGNAL(WarningMsg(QString)), this, SLOT(ShowMessageWarning(QString)));
    connect(xmlinfofile, SIGNAL(MDavInfoXmlItem(QDomDocument,QString)), this, SLOT(TreeInfo(QDomDocument,QString)));
   
}




void BaseDav::StopLoop()
{
    subdirlist.clear();
}

void BaseDav::SubTreeRegister( QString file ,QString path ,int pos )
{
   ///////////////////qDebug() << "#### SubTreeRegister save  ->" << dbdav->ResolvDisplayPath(path);
    dbdav->Register_Path(path,file,DAVM2_);
    SubinfoGrabPosition(pos);
}


void BaseDav::SubinfoGrabPosition( int now  )
{
    int bigmap = subdirlist.size();
    if (bigmap < 0) {
        ExitNextOperation();
        return;
    }
    if (now >= bigmap) {    
    subdirlist.clear(); 
    return;
    }
    
    qDebug() << "#### grab id  ->" << now << " size->" << bigmap;
    
    
    for (int i = 0; i < subdirlist.size(); ++i) {
         if (now == i) {
             QString dirname =  subdirlist.at(i);
             DavPROPFIND *xmlsubdir = new DavPROPFIND(dbdav,dbdav->ResolvDisplayPath(dirname));  /* */
             xmlsubdir->SetPosition(i);
             connect(xmlsubdir, SIGNAL(WarningMsg(QString)), this, SLOT(StopLoop()));
             connect(xmlsubdir, SIGNAL(LoopSubdir(QDomDocument,QString,int)), this, SLOT(SubTreeRegister(QDomDocument,QString,int)));
             /*LoopSubdir(pathinfofile,pathregister,next);*/
             ////////////emit StatusPrint(tr("Preloading info from path %1").arg(dbdav->ResolvDisplayPath(dirname)));
             /* dbdav->ResolvDisplayPath(dirname) */
             return;
         }
     }

}

void BaseDav::TreeInfo( QDomDocument infoxml , const QString path ) /* DAVM2_ Infodirorfile */
{
    if (!infoxml.isNull()) {
    emit BuildTreeFromRemote(infoxml,path);
    return;
    } else {
      emit StopCicleFull();  
        return;
    }
}




    

void BaseDav::ShowMessageWarning( QString msg )
{
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    
    if (mainparent->isHidden()) {
        mainparent->setVisible(true);
    }
    
    
    QMessageBox::warning(mainparent, tr("Error from Dav_Module!"),msg);
    ErrorBuil();
}


void BaseDav::ExitNextOperation()
{
    qDebug() << "#### ExitNextOperation clean destructor  ";
    
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    QApplication::restoreOverrideCursor();
    MkdirLists.clear();
    subdirlist.clear();
    Onwaitfile.clear();
    QString dirload = QString(setter.value("LastDirRemote").toString());
    ///////mainparent->NextList(dirload);
    
     if (mainparent->isHidden()) {
        mainparent->setVisible(true);
    }
    
    
    emit  WakeUpFromList(dirload); 
}




/* ################################ DIR INFO FROM PATHS (DAVM2_) #########################################*/
/*
#define DAVM1_ "OPTIONS"
#define DAVM2_ "PROPFIND"
#define DAVM3_ "PROPPATCH"
#define DAVM4_ "PUT"
#define DAVM5_ "DELETE"
#define DAVM6_ "MKCOL"
*/
/* ################################ DIR INFO FROM PATHS (DAVM2_) #########################################*/





